import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams} from 'ionic-angular';
import {HttpServicesProvider} from "../../providers/http-services/http-services";
import {UtilsProvider} from "../../providers/utils/utils";
import {ConfigProvider} from "../../providers/config/config";
import {ValidateProvider} from "../../providers/validate/validate";
import {StorageProvider} from "../../providers/storage/storage";

@IonicPage({
    segment: 'information/add/:kind/:type_id',
    defaultHistory:['HomePage','InformationPage']
})
@Component({
    selector: 'page-information-add',
    templateUrl: 'information-add.html',
})
export class InformationAddPage {
    options: any;
    type_name: any;
    template: any;
    infoData = [];
    infoBuildData = [];
    infoIdData = [];
    auto_content = '';
    checkStatus = [];
    infoTextData = [];
    //需要发送的数据
    sendData = {
        token: '',
        auto: '',
        role: 1,
        kind: 'information',
        type_id: this.navParams.get('type_id'),
        click_pay: false,
        reward: false,
        cash_deposit: 0,
        see_pay: false,
        images: [],
        data: "",
        cash_deposit_require:0.00,
        credit_require:0.00
    };
    userInfo: any;
    amoy_id: number;

    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        public httpService: HttpServicesProvider,
        public util: UtilsProvider,
        public config: ConfigProvider,
        public validate: ValidateProvider,
        public storage: StorageProvider
    ) {
        if (!this.validate.checkLogin()) {       
            this.navCtrl.push('LoginPage');
        }
    }

    ionViewCanEnter(){
        return this.validate.checkLogin();
    }

    ionViewWillEnter() {       
        if (!this.validate.checkLogin()) {//登录
            this.navCtrl.push('LoginPage', {'backPage': 'MemberPage'});
        } else {
            let userInfo = this.storage.get('userInfo');
            if (userInfo) {
                this.userInfo = JSON.parse(userInfo);
            }
        }
        this.getOptions();
    }

    //获取表单数据
    getOptions() {
        let loading = this.util.loading();
        loading.show();
        let type_id = this.navParams.get('type_id');
        let kind = this.navParams.get('kind');
        this.httpService.requestPostData('/task_info/get_option', {
            type_id: type_id,
            kind: kind
        },data => {
            loading.close();
            if (data['code'] === 200) {
                this.options = data['data']['data'];
                this.type_name = data['data']['type_name'];
                this.template = data['data']['tpl'];
                this.storage.set('rate',JSON.stringify(data['data']['rate']));
            } else {
                alert(data['message']);
            }

        });
    }

    //选择多选数据
    selCheckData(item, option) {
        if (!this.util.isArray(this.infoData[item.letter])) {
            this.infoData[item.letter] = [];
        }
        if (!this.util.isArray(this.infoBuildData[item.num])) {
            this.infoBuildData[item.num] = [];
        }
        if (!this.util.isArray(this.infoIdData[item.num])) {
            this.infoIdData[item.num] = [];
        }
        if (this.util.inArray(this.infoData[item.letter], option.list_name) < 0) {
            this.infoData[item.letter].push(option.list_name);
            this.infoBuildData[item.num].push(option.list_name);
            this.infoIdData[item.num].push(option.list_id);
        } else {
            let index = this.util.inArray(this.infoData[item.letter], option.list_name);
            if (index !== -1) {
                this.infoData[item.letter].splice(index, 1);
                this.infoBuildData[item.num].splice(index, 1)
                this.infoIdData[item.num].splice(index, 1)
            }
        }
        this.buildContent();
    }

    //单选数据
    selRadioData(item, option) {
        this.infoData[item.letter] = option.list_name;
        this.infoBuildData[item.num] = option.list_name;
        this.infoIdData[item.num] = option.list_id;
        this.infoTextData[item.letter] = '';
        this.buildContent();
    }

    //文本框数据
    textData(item) {
        if(this.infoData[item.letter] == '' || this.infoData[item.letter] == undefined){
            return;
        }
        this.infoBuildData[item.num] = this.infoData[item.letter];
        this.infoIdData[item.num] = this.infoData[item.letter];
        this.buildContent();
    }

    //多选文本框数据
    checkFocusData(item) {
        if (!this.util.isArray(this.infoData[item.letter])) {
            this.infoData[item.letter] = [];
        }
        if (!this.util.isArray(this.infoBuildData[item.num])) {
            this.infoBuildData[item.num] = [];
        }
        if (!this.util.isArray(this.infoIdData[item.num])) {
            this.infoIdData[item.num] = [];
        }
        let index = this.util.inArray(this.infoData[item.letter], this.infoTextData[item.letter]);
        if (index !== -1) {
            this.infoData[item.letter].splice(index, 1);
            this.infoBuildData[item.num].splice(index, 1);
            this.infoIdData[item.num].splice(index, 1);
        }
        this.buildContent();
    }

    checkBlurData(item) {
        if (this.infoTextData[item.letter] == undefined || this.infoTextData[item.letter] == '') {
            return false;
        }
        if (!this.util.isArray(this.infoData[item.letter])) {
            this.infoData[item.letter] = [];
        }
        if (!this.util.isArray(this.infoBuildData[item.num])) {
            this.infoBuildData[item.num] = [];
        }
        if (!this.util.isArray(this.infoIdData[item.num])) {
            this.infoIdData[item.num] = [];
        }
        this.infoData[item.letter].push(this.infoTextData[item.letter]);
        this.infoBuildData[item.num].push(this.infoTextData[item.letter]);
        this.infoIdData[item.num].push(this.infoTextData[item.letter]);
        this.buildContent();
    }

    //自动生成文本内容
    buildContent() {
        this.auto_content = this.template;
        this.infoBuildData.forEach((ele, index) => {
            let reg = new RegExp('\\[' + index + '\\]', "g");
            if (this.util.isArray(ele)) { //多选
                if (ele.length > 0) {
                    this.auto_content = this.auto_content.replace(reg, ele.join(','));
                }
            } else {
                if (ele != '') {
                    this.auto_content = this.auto_content.replace(reg, ele);
                }
            }
        });
        let reg2 = /\[\d{0,2}]/g;
        this.auto_content = this.auto_content.replace(reg2,"无");
    }

    resetData() {
        this.infoData = [];
        this.infoBuildData = [];
        this.infoTextData = [];
        this.buildContent();
    }

    /**
     * 图片上传
     * */
    uploadImage(item, e) {
        let file = e.target.files[0];
        let data = new FormData();
        data.append('image', file);
        data.append('type', 'moments');
        this.httpService.uploadImage('/user/upload_file', data, result => {
            if (!this.util.isArray(this.infoData[item.letter])) {
                this.infoData[item.letter] = [];
            }
            if (!this.util.isArray(this.infoBuildData[item.num])) {
                this.infoBuildData[item.num] = [];
            }
            if (!this.util.isArray(this.infoIdData[item.num])) {
                this.infoIdData[item.num] = [];
            }
            this.infoData[item.letter].push(result.img_path);
            this.infoBuildData[item.num].push(result.img_path);
            this.infoIdData[item.num].push(result.img_path);
        });
    }

    delImage(item, value) {
        this.util.presentConfirm('确定删除吗？', () => {
            let index = this.util.inArray(this.infoData[item.letter], value);
            if (index > -1) {
                this.infoData[item.letter].splice(index, 1);
            }
        });
    }

    /**
     * 检查用户权限
     * */
    checkLevel(type){
        let apiUrl = "/user_info/check_level";
        this.httpService.requestPostData(apiUrl,{
            token: this.config.getToken()
        }, (response)=>{
            if(response['error'] != 200 || response['reg_step'] != 2){
                this.sendData[type] = false;
                this.util.presentConfirm('无法调用高级用户权限，您可点击确定去完善注册信息，也可点击取消留在当前页面', ()=>{
                    this.navCtrl.push('RegisterPage');
                });
            }
        });
    }

    selDate(item, event){
        let year = event.year;
        let month = event.month < 10 ? '0' + event.month : event.month;
        let day = event.day;
        if(this.infoData[item.letter] == '' || this.infoData[item.letter] == undefined){
            return;
        }
        this.infoBuildData[item.num] = year + '年' + month + '月' + day + '日';
        this.infoIdData[item.num] = this.infoData[item.letter];
        this.buildContent();
    }

    /**
     * 数据提交
     * */
    submitData() {
        this.sendData.auto = this.auto_content;
        this.sendData.data = JSON.stringify(this.infoIdData);
        this.sendData.token = this.config.getToken();
        if(this.sendData['click_pay'] || this.sendData['see_pay'] || this.sendData['reward']){
            this.httpService.requestPostData('/user_info/check_level',{
                token: this.config.getToken()
            }, (response)=>{
                if(response['error'] == 200 && response['reg_step'] == 2){
                    this.storage.set('information',JSON.stringify(this.sendData));
                    this.navCtrl.push('InformationPaymentPage');
                }else{
                    this.sendData['click_pay'] = false;
                    this.sendData['see_pay'] = false;
                    this.sendData['reward'] = false;
                    this.util.presentConfirm('设置点击付费、付费查看、悬赏为高级用户权限，去完善注册信息成为高级注册用户？', ()=>{
                        this.navCtrl.push('RegisterPage');
                    });
                }
            });

        }else{
            let loadObj = this.util.loading({
                content: '数据提交中...'
            });
            let apiUrl = "/task_info/insert_option";
            this.httpService.requestPostData(apiUrl, this.sendData, data => {
                loadObj.close();
                if(data['code'] !== 200){
                    this.util.presentAlert(data['message']);
                }else{
                    this.util.presentAlert('信息发布成功');
                    // let amoy_id = data['amoy_id'];
                    // this.navCtrl.setRoot('HomePage');
                    // this.navCtrl.push('InformationDetailPage',{id:amoy_id},{
                    //     animate:true,
                    //     direction:'forward'
                    // });
                    this.navCtrl.setRoot('HomePage');
                    this.navCtrl.push('InformationPage',{nav_id:this.sendData['type_id']},{
                        animate:true,
                        direction:'forward'
                    });
                }
            })
        }


    }

}
